<template>
  <div class="account-settings">
    <!-- 头部栏 -->
    <HeaderComponent 
      :isLoggedIn="isLoggedIn"
      :userInfo="userInfo"
      :showUserPanel="showUserPanel"
      @open-login="$emit('open-login')"
      @toggle-user-panel="$emit('toggle-user-panel')"
      @logout="$emit('logout')"
    />
    
    <!-- 主布局 -->
    <div class="main-layout">
      <!-- 左侧设置导航栏 -->
      <aside class="settings-sidebar">
        <div class="sidebar-header">
          <h3>设置</h3>
        </div>
        <ul class="settings-nav">
          <li class="nav-item">
            <router-link to="/user/settings/profile" class="nav-link">
              <span class="nav-icon">👤</span>
              <span>个人资料</span>
            </router-link>
          </li>
          <li class="nav-item active">
            <router-link to="/user/settings/account" class="nav-link">
              <span class="nav-icon">🔐</span>
              <span>账号设置</span>
            </router-link>
          </li>
          <li class="nav-item">
            <router-link to="/user/settings/general" class="nav-link">
              <span class="nav-icon">⚙️</span>
              <span>通用设置</span>
            </router-link>
          </li>
          <li class="nav-item">
            <router-link to="/user/settings/notifications" class="nav-link">
              <span class="nav-icon">🔔</span>
              <span>消息设置</span>
            </router-link>
          </li>
          <li class="nav-item">
            <router-link to="/user/settings/block" class="nav-link">
              <span class="nav-icon">🚫</span>
              <span>屏蔽管理</span>
            </router-link>
          </li>
          <li class="nav-item">
            <router-link to="/user/settings/tags" class="nav-link">
              <span class="nav-icon">🏷️</span>
              <span>标签管理</span>
            </router-link>
          </li>
        </ul>
      </aside>
      
      <!-- 右侧内容区 -->
      <main class="settings-content">
        <div class="settings-header">
          <h2>账号设置</h2>
          <p>管理您的账号安全和登录信息</p>
        </div>
      <div class="form-section">
        <h3>登录信息</h3>
        <div v-if="loading" class="loading-message">正在加载账户信息...</div>
        <div class="info-item">
          <label>手机号</label>
          <div class="info-value">
            <span>{{ maskedPhone }}</span>
            <button class="btn-link" @click="showChangePhone = true">{{ account.phone ? '更换' : '添加手机号' }}</button>
          </div>
        </div>
        
        <div class="info-item">
          <label>邮箱</label>
          <div class="info-value">
            <span>{{ maskedEmail }}</span>
            <button class="btn-link" @click="showChangeEmail = true">{{ account.email ? '更换' : '添加邮箱' }}</button>
          </div>
        </div>
        
        <div class="info-item">
          <label>GitHub</label>
          <div class="info-value">
            <span>{{ displayGithub }}</span>
            <button class="btn-link" @click="bindGitHub">{{ account.githubUrl ? '解绑' : '绑定' }}</button>
          </div>
        </div>
        
        <div class="info-item">
          <label>当前密码</label>
          <div class="info-value">
            <span>{{ hasPassword ? '已设置' : '未设置' }}</span>
            <button class="btn-link" @click="showChangePassword = true">{{ hasPassword ? '修改密码' : '设置密码' }}</button>
          </div>
        </div>
      </div>
      
      <div class="form-section">
        <h3>密码管理</h3>
        <div class="form-group">
          <label>当前密码</label>
          <input type="password" v-model="passwordForm.currentPassword" placeholder="请输入当前密码" />
        </div>
        
        <div class="form-group">
          <label>新密码</label>
          <input type="password" v-model="passwordForm.newPassword" placeholder="请输入新密码" />
        </div>
        
        <div class="form-group">
          <label>确认新密码</label>
          <input type="password" v-model="passwordForm.confirmPassword" placeholder="请再次输入新密码" />
        </div>
        
        <button class="btn-primary" @click="changePassword">修改密码</button>
      </div>
      
      <div class="form-section danger-zone">
        <h3>危险操作</h3>
        <div class="danger-item">
          <div class="danger-info">
            <h4>注销账号</h4>
            <p>注销后将无法恢复，请谨慎操作</p>
          </div>
          <button class="btn-danger" @click="showDeleteConfirm = true">注销账号</button>
        </div>
      </div>
    
    
    <!-- 更换手机号弹窗 -->
    <div v-if="showChangePhone" class="modal-overlay" @click="showChangePhone = false">
      <div class="modal" @click.stop>
        <h3>{{ account.phone ? '更换手机号' : '添加手机号' }}</h3>
        <div class="form-group">
          <label>新手机号</label>
          <input type="tel" v-model="newPhone" placeholder="请输入新手机号" />
        </div>
        <div class="form-group">
          <label>验证码</label>
          <div class="verify-input">
            <input type="text" v-model="phoneCode" placeholder="请输入验证码" />
            <button class="btn-secondary" @click="sendPhoneCode">发送验证码</button>
          </div>
        </div>
        <div class="modal-actions">
          <button class="btn-primary" @click="confirmChangePhone">确认更换</button>
          <button class="btn-secondary" @click="showChangePhone = false">取消</button>
        </div>
      </div>
    </div>
    
    <!-- 更换邮箱弹窗 -->
    <div v-if="showChangeEmail" class="modal-overlay" @click="showChangeEmail = false">
      <div class="modal" @click.stop>
        <h3>更换邮箱</h3>
        <div class="form-group">
          <label>新邮箱</label>
          <input type="email" v-model="newEmail" placeholder="请输入新邮箱" />
        </div>
        <div class="form-group">
          <label>验证码</label>
          <div class="verify-input">
            <input type="text" v-model="emailCode" placeholder="请输入验证码" />
            <button class="btn-secondary" @click="sendEmailCode">发送验证码</button>
          </div>
        </div>
        <div class="modal-actions">
          <button class="btn-primary" @click="confirmChangeEmail">确认更换</button>
          <button class="btn-secondary" @click="showChangeEmail = false">取消</button>
        </div>
      </div>
    </div>
    
    <!-- 注销确认弹窗 -->
    <div v-if="showDeleteConfirm" class="modal-overlay" @click="showDeleteConfirm = false">
      <div class="modal" @click.stop>
        <h3>确认注销账号</h3>
        <p>注销后所有数据将被永久删除，此操作不可恢复。</p>
        <div class="form-group">
          <label>请输入密码确认</label>
          <input type="password" v-model="deletePassword" placeholder="请输入密码" />
        </div>
        <div class="modal-actions">
          <button class="btn-danger" @click="confirmDeleteAccount">确认注销</button>
          <button class="btn-secondary" @click="showDeleteConfirm = false">取消</button>
        </div>
      </div>
    </div>


    </main>
    </div>
    </div>
</template>

<script>
import HeaderComponent from '@/components/HeaderComponent.vue';
import { userAPI } from '@/api/index.js';

export default {
  components: {
    HeaderComponent
  },
  name: 'AccountSettings',
  props: {
    isLoggedIn: {
      type: Boolean,
      default: false
    },
    userInfo: {
      type: Object,
      default: () => ({})
    },
    showUserPanel: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      account: {
        phone: null,
        email: null,
        githubUrl: null,
        userPassword: null
      },
      loading: false,
      passwordForm: {
        currentPassword: '',
        newPassword: '',
        confirmPassword: ''
      },
      showChangePhone: false,
      showChangeEmail: false,
      showChangePassword: false,
      showDeleteConfirm: false,
      newPhone: '',
      newEmail: '',
      phoneCode: '',
      emailCode: '',
      deletePassword: ''
    }
  },
  computed: {
    maskedPhone() {
      if (!this.account.phone) return '未绑定'
      const phone = this.account.phone
      return phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')
    },
    maskedEmail() {
      if (!this.account.email) return '未绑定';
      const [name, domain] = this.account.email.split('@');
      const maskedName = name.length > 2 ? name.substring(0, 2) + '***' : name;
      return maskedName + '@' + domain;
    },
    displayGithub() {
      return this.account.githubUrl || '未绑定';
    },
    hasPassword() {
      return this.account.userPassword && this.account.userPassword.trim() !== '';
    }
  },
  async mounted() {
    await this.loadAccountInfo();
  },
  methods: {
    async loadAccountInfo() {
      try {
        this.loading = true;
        const response = await userAPI.getMyAccount();
        console.log('账户信息响应:', response);
        
        if (response.code === 0) {
          this.account = {
            phone: response.data.phone,
            email: response.data.email,
            githubUrl: response.data.githubUrl,
            userPassword: response.data.userPassword
          };
        } else {
          this.$message?.error(response.message || '获取账户信息失败');
        }
      } catch (error) {
        console.error('获取账户信息失败:', error);
        this.$message?.error('网络错误，请稍后重试');
      } finally {
        this.loading = false;
      }
    },
    changePassword() {
      if (!this.passwordForm.currentPassword) {
        this.$message?.error('请输入当前密码');
        return;
      }
      if (!this.passwordForm.newPassword) {
        this.$message?.error('请输入新密码');
        return;
      }
      if (this.passwordForm.newPassword !== this.passwordForm.confirmPassword) {
        this.$message?.error('两次输入的密码不一致');
        return;
      }
      
      console.log('修改密码:', this.passwordForm);
      this.$message?.success('密码修改成功');
      this.passwordForm = {
        currentPassword: '',
        newPassword: '',
        confirmPassword: ''
      };
    },
    sendPhoneCode() {
      // 验证手机号格式
      const phoneRegex = /^1[3-9]\d{9}$/
      if (!phoneRegex.test(this.newPhone)) {
        this.$message?.error('请输入正确的手机号')
        return
      }
      
      // 提示验证码为123456
      this.$message?.success('验证码已发送，验证码为：123456')
      console.log('发送验证码到:', this.newPhone)
    },
    sendEmailCode() {
      if (!this.newEmail) {
        this.$message?.error('请输入邮箱');
        return;
      }
      console.log('发送邮箱验证码:', this.newEmail);
      this.$message?.success('验证码已发送');
    },
    async confirmChangePhone() {
      if (!this.newPhone || !this.phoneCode) {
        this.$message?.error('请填写完整信息')
        return
      }
      
      // 验证手机号格式
      const phoneRegex = /^1[3-9]\d{9}$/
      if (!phoneRegex.test(this.newPhone)) {
        this.$message?.error('请输入正确的手机号')
        return
      }
      
      try {
        const response = await fetch('/api/user/change/phone', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          credentials: 'include',
          body: JSON.stringify({
            newPhone: this.newPhone,
            verificationCode: this.phoneCode
          })
        })
        
        const result = await response.json()
        
        if (result.code === 0) {
          this.account.phone = this.newPhone
          this.showChangePhone = false
          this.newPhone = ''
          this.phoneCode = ''
          this.$message?.success('手机号更换成功')
        } else {
          this.$message?.error(result.message || '更换手机号失败')
        }
      } catch (error) {
        console.error('更换手机号失败:', error)
        this.$message?.error('网络错误，请稍后重试')
      }
    },
    confirmChangeEmail() {
      if (!this.emailCode) {
        this.$message?.error('请输入验证码');
        return;
      }
      this.account.email = this.newEmail;
      this.showChangeEmail = false;
      this.newEmail = '';
      this.emailCode = '';
      this.$message?.success('邮箱更换成功');
    },
    bindGitHub() {
      if (this.account.githubUrl) {
        this.account.githubUrl = null;
        this.$message?.success('GitHub解绑成功');
      } else {
        // 模拟GitHub绑定
        this.account.githubUrl = 'github_user';
        this.$message?.success('GitHub绑定成功');
      }
    },
    confirmDeleteAccount() {
      if (!this.deletePassword) {
        this.$message?.error('请输入密码');
        return;
      }
      console.log('注销账号');
      this.$message?.success('账号注销成功');
      this.showDeleteConfirm = false;
      // 这里应该跳转到登录页面
      this.$router.push('/');
    }
  }
}
</script>

<style scoped>
.account-settings {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.main-layout {
  display: flex;
  max-width: 1200px;
  margin: 0 auto;
  background-color: white;
  min-height: calc(100vh - 60px);
}

.settings-sidebar {
  width: 250px;
  background-color: #fff;
  border-right: 1px solid #e5e5e5;
  padding: 20px 0;
}

.sidebar-header {
  padding: 0 20px 20px;
  border-bottom: 1px solid #e5e5e5;
}

.sidebar-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.settings-nav {
  list-style: none;
  padding: 0;
  margin: 0;
}

.nav-item {
  margin: 0;
}

.nav-link {
  display: flex;
  align-items: center;
  padding: 12px 20px;
  text-decoration: none;
  color: #666;
  transition: all 0.3s;
}

.nav-link:hover {
  background-color: #f8f9fa;
  color: #007bff;
}

.nav-item.active .nav-link {
  background-color: #e3f2fd;
  color: #007bff;
  border-right: 3px solid #007bff;
}

.nav-icon {
  margin-right: 10px;
  font-size: 16px;
}

.settings-content {
  flex: 1;
  padding: 20px;
  max-width: 800px;
}

.settings-header {
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #e5e5e5;
}

.settings-header h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #333;
}

.settings-header p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.form-section {
  margin-bottom: 30px;
  padding: 20px;
  background: #f9f9f9;
  border-radius: 8px;
}

.form-section h3 {
  margin: 0 0 20px 0;
  font-size: 18px;
  color: #333;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #e5e5e5;
}

.info-item:last-child {
  border-bottom: none;
}

.info-item label {
  font-weight: 500;
  color: #333;
  min-width: 80px;
}

.info-value {
  display: flex;
  align-items: center;
  gap: 12px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.form-group input {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.3s;
}

.form-group input:focus {
  outline: none;
  border-color: #007bff;
}

.verify-input {
  display: flex;
  gap: 12px;
}

.verify-input input {
  flex: 1;
}

.btn-primary,
.btn-secondary,
.btn-danger,
.btn-link {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.btn-primary {
  background-color: #007bff;
  color: white;
}

.btn-primary:hover {
  background-color: #0056b3;
}

.btn-secondary {
  background-color: #6c757d;
  color: white;
}

.btn-secondary:hover {
  background-color: #545b62;
}

.btn-danger {
  background-color: #dc3545;
  color: white;
}

.btn-danger:hover {
  background-color: #c82333;
}

.btn-link {
  background: none;
  color: #007bff;
  padding: 4px 8px;
  text-decoration: underline;
}

.btn-link:hover {
  color: #0056b3;
}

.danger-zone {
  border: 1px solid #dc3545;
  background: #fff5f5;
}

.danger-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.danger-info h4 {
  margin: 0 0 4px 0;
  color: #dc3545;
}

.danger-info p {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal {
  background: white;
  padding: 24px;
  border-radius: 8px;
  width: 90%;
  max-width: 400px;
}

.modal h3 {
  margin: 0 0 20px 0;
  color: #333;
}

.modal-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
  margin-top: 20px;
}

.loading-message {
  text-align: center;
  color: #666;
  font-style: italic;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 4px;
  margin-bottom: 20px;
}
</style>